package com.jaychan.oauth;

import com.jaychan.utils.JwtOperator;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author JayChan
 * @Description
 * @create 2022-01-11 9:17 PM
 */

@Aspect
@Component
@RequiredArgsConstructor
public class AuthAspect {

    private final JwtOperator jwtOperator;


    @Around("@annotation(com.jaychan.oauth.CheckLogin)")
    public Object checkLogin(ProceedingJoinPoint joinPoint) {

        try {
            //1.从header获取token
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("X-Token");

            //2.校验token是否合法&是否过期，如果不合法，跑异常，合法放行
            Boolean valid = jwtOperator.validateToken(token);
            if (!valid) {
                throw new SecurityException("token不合法");
            }

            //3.校验成功，将用户信息设置到request的attribute
            Claims claims = jwtOperator.getClaimsFromToken(token);
            request.setAttribute("id",claims.get("id"));


            //直接放行执行方法
            return joinPoint.proceed();
        } catch (Throwable e) {
            throw new SecurityException("token不合法");
        }
    }


//    @Around("@annotation(com.jaychan.oauth.CheckAuthorization)")
//    public Object checkLogin(ProceedingJoinPoint joinPoint) {
//
//
//
//    }
}
